package http

import (
	"StudentClient/client"
	"StudentClient/protos"
	"github.com/gin-gonic/gin"
	"log"
)

const address = "localhost:8080"

func StartHttpServer() {
	serviceClient, conn, err := client.ConnectServer()
	if err != nil {
		log.Fatalln(err.Error())
	}
	defer conn.Close()

	eng := gin.New()

	eng.GET("/student/:id", handlerWithContext(serviceClient, findOneHandler))
	eng.POST("/student", handlerWithContext(serviceClient, addHandler))
	eng.PUT("/student", handlerWithContext(serviceClient, updateHandler))
	eng.DELETE("/student/:id", handlerWithContext(serviceClient, deleteHandler))
	eng.GET("/students", handlerWithContext(serviceClient, listAllHandler))

	err = eng.Run(address)
	if err != nil {
		log.Fatalln(err.Error())
	}
}

type RPCContext struct {
	*gin.Context
	stuClient protos.StudentServiceClient
}

type handlerFunc func(*RPCContext)

func handlerWithContext(serviceClient protos.StudentServiceClient, handler handlerFunc) gin.HandlerFunc {
	return func(context *gin.Context) {
		rpcCtx := new(RPCContext)
		rpcCtx.Context = context
		rpcCtx.stuClient = serviceClient
		handler(rpcCtx)
	}
}
